﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Data;
using TracNghiemTinHocDaiCuong.ThucThe;
using TracNghiemTinHocDaiCuong.BIZ;
using TracNghiemTinHocDaiCuong.Common;

namespace TracNghiemTinHocDaiCuong
{
    public partial class DangKi : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void txtTenTaiKhoan_Changed(object sender, EventArgs e)
        {
            NguoiDung tim = NguoiDungBIZ.TimKiemTheoTenTaiKhoan(txtTenTaiKhoan.Text);
            if (tim != null)
            {
                divThongBao.InnerText = "Tài khoản hợp lệ.";
                divThongBao.Attributes.Add("class", "KhongTrungTen");
            }
            else
            {
                divThongBao.InnerText = "Tên tài khoản đã được sử dụng";
                divThongBao.Attributes.Add("class", "TrungTen");
            }
        }


        protected void btnDangKi_Click(object sender, EventArgs e)
        {
            NguoiDung nguoiDungMoi = new NguoiDung();
            NguoiDung tim = NguoiDungBIZ.TimKiemTheoTenTaiKhoan(txtTenTaiKhoan.Text);
            nguoiDungMoi.TenTaiKhoan = txtTenTaiKhoan.Text;
            MD5 md5Hash = MD5.Create();
            string hash = MethodHelper.LayBangBamMD5(md5Hash, txtMatKhau.Text);
            nguoiDungMoi.MatKhau = hash;
            nguoiDungMoi.HoVaTen = txtHoTen.Text;
            nguoiDungMoi.NgaySinh = Methods.ConvertDateTime(ConvertDateTimeToString(txtNgaySinh.Text));
            nguoiDungMoi.Email = txtEmail.Text;
            nguoiDungMoi.GioiTinh = rblGioiTinh.SelectedValue;
            nguoiDungMoi.DienThoai = txtDienThoai.Text;
            nguoiDungMoi.DiaChi = txtDiaChi.Text;
            nguoiDungMoi.NgayDangKi = DateTime.Now;
            NguoiDungBIZ.Them(nguoiDungMoi);
            lblThongBao.Text = "Bạn đã đăng kí tài khoản " + txtTenTaiKhoan.Text + " thành công";
        }

        private string ConvertDateTimeToString(string exp)
        {
            if (string.IsNullOrEmpty(exp))
                return "04/01/2013";
            string[] time = exp.Split('/');
            if (Methods.ConvertNumber(time[0]) > 23)
                return "04/01/2013";
            if (Methods.ConvertNumber(time[1]) > 59)
                return "04/01/2013";
            return string.Format(CultureInfo.CurrentCulture, "{0}/{1}/{2}",
                time[1], time[0], time[2]);
        }
    }
}